
(function () {
    var checkedUser;

    function renderSelectUser(container, obj){

        var html = '<div class="list-block accordion-list"><ul>';

        if(obj.children.length > 0){
            $$.each(obj.children, function(index, el){
                if ( el.children.length > 0 ){

                    html += '<li class="accordion-item">'+
                        '<label class="label-checkbox">'+
                        '<input type="checkbox" data-type="depart" data-id="'+ el.id +'" name="" value="">'+
                        '<div class="item-media">'+
                        '<i class="icon icon-form-checkbox"></i>'+
                        '</div>'+
                        '</label>'+
                        '<a href="#" class="item-content item-link" data-deaprtId="'+ el.id +'">'+
                        '<div class="item-inner">'+
                        '<div class="item-title">'+ el.label +'</div>'+
                        '</div>'+
                        '</a>'+
                        '<div class="accordion-item-content">';

                    html += renderSelectUser(container, el);

                    html += '</div></li>';
                } else {
                    html += '<li class="accordion-item deep-item">'+
                        '<label class="label-checkbox">'+
                        '<input type="checkbox" data-type="depart" data-id="'+ el.id +'" name="" value="">'+
                        '<div class="item-media">'+
                        '<i class="icon icon-form-checkbox"></i>'+
                        '</div>'+
                        '</label>'+
                        '<a href="#" class="item-content item-link" data-deaprtId="'+ el.id +'">'+
                        '<div class="item-inner">'+
                        '<div class="item-title">'+ el.label +'</div>'+
                        '</div>'+
                        '</a>'+
                        '<div class="accordion-item-content">';
                    html += '</div></li>';
                }
            });
        }

        html += '</ul></div>';

        return html;
    };

    function renderUserList(container, searchList, deaprtId, link, hasSubDepart){
        var html = '';

        //myApp.showIndicator();
        $$.getJSONP(SERVER_PATH + 'listuser.do', {"deaprtId": deaprtId}, function (json) {
            if ( json.code == 1 ){
                link.data('loaded', true);

                var userData = json.results;

                html += '<div class="list-block media-list user-list"><ul>';

                if(userData.length > 0){
                    $$.each(userData, function(index, el){

                        var avatarPath = PORTRAIT_PATH + el.id + '.jpg';
                        el['avatar'] = avatarPath;

                        var li = '<li>' +
                            '<label class="item-content label-checkbox">' +
                            '<input type="checkbox" data-type="user" data-userinfo={'+ JSON.stringify(el).replace(/[\{ \}]/g, "") +'} data-id="' + el.id + '" name="" value="">' +
                            '<div class="item-media">' +
                            '<img src="' + el.avatar + '" width="44" height="44">' +
                            '<a href="#" class="link"><i class="icon icon-form-checkbox"></i></a>' +
                            '</div>' +
                            '<div class="item-inner">' +
                            '<div class="item-title">' + el.firstName + '</div>' +
                            '</div>' +
                            '</label>' +
                            '</li>';

                        html += li;

                        searchList.find('ul').append(li);
                    });
                } else if(hasSubDepart) {
                    html += '';
                } else {
                    var uid = $$.uniqueName();

                    html += '<li data-uid='+ uid +'>'+
                        '<div class="item-content">'+
                        '<div class="item-inner">'+
                        '<div class="item-subtitle">暂无成员！</div>'+
                        '</div>'+
                        '</div>'+
                        '</li>';

                    setTimeout(function(){
                        $$('[data-uid='+ uid + ']').parents('li.accordion-item.deep-item').find('label').addClass('disabled').find('input[type="checkbox"]').remove();
                    }, 0)
                }

                html += '</ul></div>';

                container.find('.item-link[data-deaprtId="' + deaprtId + '"]').next('.accordion-item-content').prepend(html);
                renderSelectArea(container);
                //myApp.hideIndicator();
                //pageCon.find(".deep-item .item-link").trigger('loaddata');
            }
        });
    }

    function isAllChildrenChecked (input) {
        var li = input.parents("li").eq(0);
        var children = li.find('input[type="checkbox"][data-type="user"]');
        var allChecked = children.length === 0 ? false : true;

        for (var i = 0; i < children.length; i++) {
            if (!children.eq(i).prop('checked')) {
                allChecked = false;
                break;
            }
        }
        return allChecked;
    }

    function renderSelectArea (container) {
        //var liHtml = '';
        //
        //$$.each(checkedUser, function(key, el){
        //    liHtml += '<li class="item">'+
        //        '<div class="delete-user" data-id="' + key + '">×</div>' +
        //        '<img src="'+ (el.avatar ? el.avatar : 'image/avatar/default-avatar.jpg') +'" width="44" height="44">'+
        //        '<p>'+ el.name +'</p>'+
        //        '</li>';
        //});
        //container.find('.selectedUserList').html(liHtml);

        var area = container.find('.selectedUserList');
        $$.each(checkedUser, function(key, el) {
            if (area.find('div[data-id="' + key + '"]').length === 0) {
                area.append('<li class="item">' +
                    '<div class="delete-user" data-id="' + key + '">×</div>' +
                    '<img src="' + (el.avatar ? el.avatar : 'image/avatar/default-avatar.jpg') + '" width="44" height="44">' +
                    '<p>' + el.name + '</p>' +
                    '</li>');
            }
        });
        area.children('li.item').each(function() {
            var key = $$(this).children('div.delete-user').attr('data-id');
            if (!checkedUser[key]) {
                $$(this).remove();
            }
        });


        container.find('input[type="checkbox"][data-type="user"]').each(function () {
            var input = $$(this),
                userId = input.data('id');
            input.prop('checked', checkedUser[userId] !== undefined);
        });
        container.find('input[type="checkbox"][data-type="depart"]').each(function () {
            var input = $$(this);
            input.prop('checked', isAllChildrenChecked(input));
        });
    }

    function pushCheckedUser (input) {
        var userinfo = JSON.parse($$(input).data("userinfo"));
        userinfo.name = userinfo.firstName;

        var key = userinfo.id;
        if(!checkedUser[key]){
            checkedUser[key] =  userinfo;
        }
    }

    function deleCheckedUser (input) {
        var userinfo = JSON.parse($$(input).data("userinfo"));

        var key = userinfo.id;
        if(checkedUser[key]){
            delete checkedUser[key];
        }
    }

    //选择联系人页面
    myApp.onPageInit("selectUser", function (page) {
        var pageCon = $$(page.container);
        var delegateName = page.query.delegate,
            delegate = window[delegateName];
        window[delegateName] = undefined;

        pageCon.find('.list-block-search').hide();
        var mySearchbar = myApp.searchbar(pageCon.find('.searchbar'), {
            searchList: '.list-block-search',
            searchIn: '.item-title, .item-subtitle',
            onSearch: function (s) {
                setTimeout(function () {
                    if (s.query.length === 0) {
                        pageCon.find('.list-block-search').hide();
                        pageCon.find('.accordion-list').show();
                    } else {
                        pageCon.find('.list-block-search').show();
                        pageCon.find('.accordion-list').hide();
                    }
                }, 0);
            }
        });

        checkedUser = $.extend({}, delegate.selectedUsers);

        //选人示例数据（2015-09-23）
        // var checkedUser = {
        //     1266140: {
        //         avatar: "http://scut-oa.wisedu.com:80/sixx/CONFIRMIMAGE/headportrait/1266104.jpg",
        //         departIds: "277386",
        //         firstName: "校领导副职",
        //         id: 1266140,
        //         name: "校领导副职"
        //     },
        //     1266180: {
        //         avatar: "http://scut-oa.wisedu.com:80/sixx/CONFIRMIMAGE/headportrait/1266104.jpg",
        //         departIds: "277389,283768",
        //         firstName: "秘书科普通用户",
        //         id: 1266180,
        //         name: "秘书科普通用户"
        //     }
        // }
        
        pageCon.on("change", 'input[type="checkbox"]', $$.delayHandler(function (e){

            var input = $$(this),
                li = input.parents("li").eq(0),
                checked = input.prop('checked'),
                type = input.attr('data-type');

            if (checked) {
                if (type === 'user') {
                    pushCheckedUser(input);
                } else if (type === 'depart') {
                    li.find('input[type="checkbox"]').prop('checked', true);
                    li.find('input[type="checkbox"][data-type="user"]').each(function (index, el) {
                        pushCheckedUser(el);
                    });
                }
            } else {
                if (type === 'user') {
                    deleCheckedUser(input);
                } else if (type === 'depart') {
                    li.find('input[type="checkbox"]').prop('checked', true);
                    li.find('input[type="checkbox"][data-type="user"]').each(function (index, el) {
                        deleCheckedUser(el);
                    });
                }
            }

            renderSelectArea(pageCon);
        }));
       
        		
        $$.getJSONP(SERVER_PATH + 'listdepart.do', null, function (json) {
            if (json.code == 1) {
                var addressBookData = json.results[0];
                var html = '<div class="list-block accordion-list"><ul>'+
                                '<li class="accordion-item">'+
                                    '<label class="label-checkbox">'+
                                        '<input type="checkbox" data-type="depart" data-deaprtId="'+ addressBookData.id +'" data-id="'+ addressBookData.id +'" name="" value="">'+
                                        '<div class="item-media">'+
                                            '<i class="icon icon-form-checkbox"></i>'+
                                        '</div>'+
                                    '</label>'+
                                    '<a href="#" class="item-content item-link" data-deaprtId="'+ addressBookData.id +'" data-id="'+ addressBookData.id +'">'+
                                        '<div class="item-inner">'+
                                          '<div class="item-title">'+ addressBookData.label +'</div>'+
                                        '</div>'+
                                    '</a>'+
                                    '<div class="accordion-item-content">';
                html += renderSelectUser(pageCon, addressBookData);
                html += '</div></li>';
                html += '</ul></div>';
              
                pageCon.find('.selectUser').prepend(html);           
                //pageCon.find(".item-link").trigger('loaddata');
                pageCon.on("click loaddata", ".item-link", function(e){
                    var link = $$(this),
                        deaprtId = link.data("deaprtId"),
                        hasSubDepart = $$(this).parent().find('.accordion-list').length > 0;

                    if (link.data('loaded')) {
                        return;
                    }

                    renderUserList(pageCon, mySearchbar.searchList, deaprtId, link, hasSubDepart);
                });
              
                pageCon.find(".selectedUserArea .completeBtn").on("click", function(e){
                    delegate.delegate(checkedUser);
                    page.view.back();
                });
            }
        });
    });


    myApp.onPageInit("selectUser-pad", function (page) {
        console.log("onPageInit " + page.name);
        var pageCon = $$(page.container);
        var delegateName = page.query.delegate,
            delegate = window[delegateName];
        window[delegateName] = undefined;
        var subpages = pageCon.find('.subpage-content');

        pageCon.find('.list-block-search').hide();
        var mySearchbar = myApp.searchbar(pageCon.find('.searchbar'), {
            searchList: '.list-block-search',
            searchIn: '.item-title, .item-subtitle',
            onSearch: function (s) {
                setTimeout(function () {
                    if (s.query.length === 0) {
                        pageCon.find('.list-block-search').hide();
                        pageCon.find('.accordion-list').show();
                        subpages.eq(0).css('width', '30%');
                        subpages.eq(1).show();
                        subpages.eq(2).css('width', '40%');
                    } else {
                        pageCon.find('.list-block-search').show();
                        pageCon.find('.accordion-list').hide();
                        subpages.eq(0).css('width', '40%');
                        subpages.eq(1).hide();
                        subpages.eq(2).css('width', '60%');
                    }
                }, 0);
            }
        });

        checkedUser = $.extend({}, delegate.selectedUsers);

        function loadSelectArea() {
            var link = $$(this),
                list = subpages.eq(1).find('.list-block');
            var hideList = link.next('.accordion-item-content').find('.user-list');

            if (list.data('list-el') !== hideList[0]) {
                list.data('list-el', hideList[0])
                list.children().remove();
                if (hideList.length > 0) {
                    list.append(hideList.eq(0).html());
                    renderSelectArea(pageCon);
                }
            }
        }
        pageCon.on("change", 'input[type="checkbox"]', $$.delayHandler(function (e){

            var input = $$(this),
                li = input.parents("li").eq(0),
                checked = input.prop('checked'),
                type = input.attr('data-type');

            if (checked) {
                if (type === 'user') {
                    pushCheckedUser(input);
                } else if (type === 'depart') {
                    li.find('input[type="checkbox"]').prop('checked', true);
                    li.find('input[type="checkbox"][data-type="user"]').each(function (index, el) {
                        pushCheckedUser(el);
                    });
                }
            } else {
                if (type === 'user') {
                    deleCheckedUser(input);
                } else if (type === 'depart') {
                    li.find('input[type="checkbox"]').prop('checked', true);
                    li.find('input[type="checkbox"][data-type="user"]').each(function (index, el) {
                        deleCheckedUser(el);
                    });
                }
            }

            renderSelectArea(pageCon);

            var link = input.parent('.label-checkbox').nextAll('.item-link').eq(0);
            if (link.length > 0) {
                loadSelectArea.call(link);
            }
        }));
        pageCon.on("click loaddata", ".item-link", function(e){
            var link = $$(this),
                deaprtId = link.data("deaprtId"),
                hasSubDepart = $$(this).parent().find('.accordion-list').length > 0;

            if (link.data('loaded')) {
                return;
            }

            renderUserList(pageCon, mySearchbar.searchList, deaprtId, link, hasSubDepart);
        });
        pageCon.on("click", ".item-link", loadSelectArea);
        pageCon.on("click", ".delete-user", function (e) {
            var userId = $$(this).attr('data-id');

            delete checkedUser[userId];
            renderSelectArea(pageCon);
        });

        $$.getJSONP(SERVER_PATH + 'listdepart.do', null, function (json) {
            if (json.code == 1) {
                var addressBookData = json.results[0];
                var html = '<div class="list-block accordion-list"><ul>'+
                    '<li class="accordion-item">'+
                    '<label class="label-checkbox">'+
                    '<input type="checkbox" data-type="depart" data-deaprtId="'+ addressBookData.id +'" data-id="'+ addressBookData.id +'" name="" value="">'+
                    '<div class="item-media">'+
                    '<i class="icon icon-form-checkbox"></i>'+
                    '</div>'+
                    '</label>'+
                    '<a href="#" class="item-content item-link" data-deaprtId="'+ addressBookData.id +'" data-id="'+ addressBookData.id +'">'+
                    '<div class="item-inner">'+
                    '<div class="item-title">'+ addressBookData.label +'</div>'+
                    '</div>'+
                    '</a>'+
                    '<div class="accordion-item-content">';
                html += renderSelectUser(pageCon, addressBookData);
                html += '</div></li>';
                html += '</ul></div>';

                subpages.eq(0).prepend(html);

                pageCon.find(".item-link").trigger('loaddata');

                pageCon.find(".selectedUserArea .completeBtn").on("click", function(e){
                    delegate.delegate(checkedUser);
                    page.view.back();
                });
            }
        });
    });
}());

